package com.ruoyi.service.impl;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.service.IRegionService;
import com.ruoyi.web.domain.Region;
import com.ruoyi.web.mapper.CategoryRegionRelationMapper;
import com.ruoyi.web.mapper.GrDetailMapper;
import com.ruoyi.web.mapper.RegionMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class RegionServiceImpl implements IRegionService {
    @Resource
    private RegionMapper regionMapper;
    @Resource
    private GrDetailMapper grDetailMapper;
    @Resource
    private CategoryRegionRelationMapper categoryRegionRelationMapper;

    @Override
    public List<Region> selectRegionList(Region region) {
        return regionMapper.selectRegionList(region);
    }

    @Override
    public Integer updateRegion(Region region) {
        Region exist = regionMapper.selectRegionById(region.getId());
        if(Objects.isNull(exist)){
            throw new RuntimeException("地区不存在 无法更新");
        }
        exist.setRegionName(region.getRegionName());
         regionMapper.updateRegion(exist);
        return 1;
    }

    @Override
    public Region selectRegionById(Integer regionId) {
        return regionMapper.selectRegionById(regionId);
    }

    @Override
    public Integer saveRegion(Region role) {
        if(StringUtils.isEmpty(role.getRegionName())){
            throw new RuntimeException("地区名称不能为空");
        }
        return regionMapper.saveRegion(role);
    }

    @Override
    @Transactional
    public Integer deleteRegionById(Integer regionId) {
        // 删除跟该地区相关的所有商品分类与地区关系
        categoryRegionRelationMapper.deleteRelationByRegionId(regionId);
        grDetailMapper.deleteGrDetailByVcrId(regionId);
        return regionMapper.deleteRegionById(regionId);
    }
}
